package cn.bugstack.ai.service;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.web.socket.WebSocketSession;

import java.util.List;

import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;

/**
 * SessionManager 单元测试
 * 
 * @author bugstack
 */
class SessionManagerTest {
    
    private SessionManager sessionManager;
    private WebSocketSession mockSession;
    
    @BeforeEach
    void setUp() {
        sessionManager = new SessionManager();
        mockSession = mock(WebSocketSession.class);
        when(mockSession.getId()).thenReturn("test-session-123");
        when(mockSession.isOpen()).thenReturn(true);
    }
    
    @Test
    void testAddSession() {
        sessionManager.addSession("test-session-123", mockSession);
        assertEquals(1, sessionManager.getSessionCount());
        assertTrue(sessionManager.hasSession("test-session-123"));
    }
    
    @Test
    void testRemoveSession() {
        sessionManager.addSession("test-session-123", mockSession);
        sessionManager.removeSession("test-session-123");
        assertEquals(0, sessionManager.getSessionCount());
        assertFalse(sessionManager.hasSession("test-session-123"));
    }
    
    @Test
    void testGetSession() {
        sessionManager.addSession("test-session-123", mockSession);
        WebSocketSession retrieved = sessionManager.getSession("test-session-123");
        assertNotNull(retrieved);
        assertEquals(mockSession, retrieved);
    }
    
    @Test
    void testChatHistory() {
        sessionManager.addSession("test-session-123", mockSession);
        sessionManager.addMessage("test-session-123", "Hello");
        sessionManager.addMessage("test-session-123", "World");
        
        List<String> history = sessionManager.getHistory("test-session-123");
        assertEquals(2, history.size());
        assertEquals("Hello", history.get(0));
        assertEquals("World", history.get(1));
    }
    
    @Test
    void testGetRecentHistory() {
        sessionManager.addSession("test-session-123", mockSession);
        for (int i = 1; i <= 10; i++) {
            sessionManager.addMessage("test-session-123", "Message " + i);
        }
        
        List<String> recent = sessionManager.getRecentHistory("test-session-123", 3);
        assertEquals(3, recent.size());
        assertEquals("Message 8", recent.get(0));
        assertEquals("Message 9", recent.get(1));
        assertEquals("Message 10", recent.get(2));
    }
    
    @Test
    void testClearHistory() {
        sessionManager.addSession("test-session-123", mockSession);
        sessionManager.addMessage("test-session-123", "Hello");
        sessionManager.clearHistory("test-session-123");
        
        List<String> history = sessionManager.getHistory("test-session-123");
        assertEquals(0, history.size());
    }
}
